<?php

namespace App\Services\Topic;

use App\Constants\CodeData;
use App\Model\Topic;
use App\Model\TopicReply;
use App\Model\TopicZan;
use App\Services\Mission\MissionQueue;
use App\Services\PushMessageService;
use App\Utils\FunUtil;
use App\Utils\RedisClient;
use Hyperf\Context\Context;
use Hyperf\DbConnection\Db;
use function Hyperf\Translation\trans;

class TopicReplyService
{

    /**
     * Note - 回贴
     * DateTime 2024/7/22 18:19
     * User Admin
     * @param mixed $user
     * @param array $all
     * @return array
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     * @throws \RedisException
     * @throws \Throwable
     */
    public function reply(mixed $user, array $all)
    {
        $uid = $user['id'];
        $reply_uid = $all['reply_uid'] ?? 0;
        $topic_id = $all['topic_id'];
        $reply_id = $all['reply_id'] ?? 0;
        $content = $all['content'];
        $language = Context::get('language', 'en');
        // 禁言判断
        if (FunUtil::gagUserChat($uid)) {
            return formatData(array('result' => 0), 200, CodeData::NEED_TIPS, '账号异常正在风险审核中，审核通过才可以使用该功能，请耐心等候。');
        }
        $topic = Topic::query()->where('id', $topic_id)->first();

        if (empty($topic)) {
            return formatData(array('result' => 4), 200, CodeData::NEED_TIPS, '帖子不存在');
        }
        $topic = modelToArray($topic);

        $data = $arr = array();
        $data['uid'] = $uid;
        $data['time'] = time();
        $data['status'] = 0; //0 正常 1被举报
        $data['reply_uid'] = $reply_uid;
        $data['reply_id'] = $reply_id;
        $data['content'] = $content;
        $data['t_id'] = $topic_id;
        $rs = TopicReply::query()->insertGetId($data);

        if (empty($rs)) {
            // Tool::JSON(\CodeData::NEED_TIPS, array('result' => 5), '回帖失败');
            return formatData(array('result' => 5), 200, CodeData::NEED_TIPS, '回帖失败');
        } else {
            $arr['reply_count'] = (int)$topic['reply_count'] + 1;
            Topic::query()->where('id', $topic_id)->update($arr);

            MissionQueue::comment($uid, $user['sex']);

            $key = "topic:reply_push_message_record_{$topic['uid']}";
            $redisConn = RedisClient::getInstance();
            if (!$redisConn->exists($key)) {
                // 加入友盟消息推送队列
                PushMessageService::putUMengMsgQueue($topic['uid'], trans('message.你的动态收到一条评论，快去看看吧~', [], $language), 'com.xun.liao', $uid);
                $redisConn->set($key, date('H:i:s'), 3600); // 标记这个用户已经推过，一个小时过期
            }
            return formatData(array('result' => 1), 200, CodeData::SUCCESS, '回帖成功');
        }
    }

    /**
     * Note - 点赞
     * DateTime 2024/7/22 19:01
     * User Admin
     * @param mixed $user
     * @param array $all
     * @return array
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     * @throws \RedisException
     * @throws \Throwable
     */
    public function zan(mixed $user, array $all)
    {
        $uid = $user['id'];
        $id = $all['id'] ?? 0;
        $sub_type = $all['sub_type'] ?? 1; // 1-帖子; 2-回帖
        $type = $all['type'] ?? 1; // 1-点赞; 0-取消点赞
        $language = Context::get('language', 'en');
        $topic = Topic::query()->where('id', $id)->first();
        if (empty($topic)) {
            return formatData(array('result' => 4), 200, CodeData::NEED_TIPS, '帖子不存在');
        }
        $topic = modelToArray($topic);
        if ((new TopicZan())->add($id, $uid, $type, $sub_type)) {
            $cb['result'] = 1;
            $cb['msg'] = '操作成功';
            MissionQueue::like($uid, $user['sex']);

            $key = "topic:zan_push_message_record_{$sub_type}_{$id}";
            $redisConn = RedisClient::getInstance();
            if (!$redisConn->exists($key)) {
                PushMessageService::putUMengMsgQueue($topic['uid'], trans('message.你的动态收到一条点赞，快去看看吧~', [], $language), 'com.xun.liao', $uid);
                $redisConn->set($key, date('H:i:s'), 3600); // 标记这个用户已经推过，一个小时过期
            }
        } else {
            $cb['result'] = 4;
            $cb['msg'] = '操作失败';
        }

        return formatData($cb);
    }


    /**
     * Note - 删除回帖
     * DateTime 2024/7/22 19:01
     * User Admin
     * @param array $id
     * @return array
     */
    public function delete(array $id)
    {
        try {
            Db::beginTransaction();
            $delete = false;
            foreach ($id as $v) {
                $reply = TopicReply::query()->where('id', $v)->first();
                if (empty($reply)) {
                    return formatData(array('result' => 4), 200, CodeData::NEED_TIPS, '回帖不存在');
                }
                $rs = $reply->delete();
                if ($rs) {
                    $delete = true;
                    Topic::query()->where('id', $reply['t_id'])->decrement('reply_count');
                }
            }
            if ($delete) {
                Db::commit();
                return formatData(array('result' => 1), 200, CodeData::NEED_TIPS, '回帖删除成功');
            } else {
                Db::rollBack();
                return formatData(array('result' => 4), 200, CodeData::NEED_TIPS, '回帖删除失败');
            }
        } catch (\Exception $e) {
            Db::rollBack();
            return formatData(array('result' => 4), 200, CodeData::NEED_TIPS, '回帖删除失败');
        }


    }
}